/**
 * Created by hejg on 2018/5/16.
 */
import React, {Component} from 'react';
import {
    ScrollView,
    View,
    Text,
    StyleSheet,
    TouchableOpacity,
    TouchableHighlight
} from 'react-native';
import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import Echarts from 'native-echarts';
import Header from '../../components/Header';
import DropDown from '../../components/DropDown';
import Indicator from '../../components/Indicator';
import Style from '../../components/Style';
import Tool from '../../components/Tool';
var Dimensions = require('Dimensions');
// const HeaderRight = withNavigation(class HeaderRight extends Component {
//     render() {
//         return (<TouchableOpacity
//             onPress={() => this.props.navigation.navigate('Map',{headerTitle:new Date().getTime()+'',})}>
//             <Text style={{color:'#FFFFFF',fontSize:Style.fontSize.normal}}>测试</Text>
//         </TouchableOpacity>);
//     }
// })

export default class OperateIndexScreen extends Component {
    static navigationOptions = ({navigation}) => {
        const {params} = navigation.state;
        return {
            header: <Header headerTitle={params ? params.headerTitle : ''}/>
            // title: params ? params.title : 'A Nested Details Screen',
        }
    };

    constructor(props) {
        super(props);
        this.param = {indexCode: this.props.navigation.getParam('indexCode'), opTime: '', orgId: 0};
        this.state = {
            selectPeriodIndex: 0,//默认选中账期的第1个下标
            periodOption: [],//可供选择的账期列表
            echartsOption: {},//历史趋势图的数据
            downLevel: [{orgId: 0, orgName: '当前'}],//下载层级缓存
            downloadFlag: false,//是否可以下钻的标识
            indexData: {value: 0, ratio: 0},//最新的日指标值和同比值
            tableData: [],//数据记录
            indicator: {visible: true, message: ''},//控制遮罩层,
            indexName:this.props.navigation.getParam('headerTitle'),
        };
    }

    componentDidMount() {
        this._loadScreenData();
    }

    _loadScreenData() {
        let qr_params = "";
        for (key in this.param) {
            qr_params += ("&" + key + "=" + this.param[key]);
        }
        qr_params = qr_params.substring(1);
        let _this = this;
        Tool.fetchAjax(Tool.appPath.mkst + 'homePageIndex/indexDetailInfo', qr_params, function (data) {
            if (data.state) {
                let {charts, period, flag, list} = data.info;
                _this._handleSelectPeriod(period);
                _this._handleEchartsOption(charts);
                if (charts && charts.length > 0) {
                    _this.setState({
                        indexData: {
                            value: charts[charts.length - 1].INDEX_VALUE,
                            ratio: charts[charts.length - 1].SPECIFIC_VALUE,
                        }
                    });
                }
                _this.setState({downloadFlag: flag});
                _this.setState({tableData: list});
                _this.setState({indicator: {visible: false, message: ''}});
            } else {
                _this.setState({indicator: {visible: true, message: data.info}});
            }
        }, function (error) {
            _this.setState({indicator: {visible: true, message: error}});
        }, function () {

        });
    }

    _handleSelectPeriod(period) {
        let options = [];
        for (let i = 0; i < period.length; i++) {
            options.push({label: period[i], value: period[i]});
        }
        this.setState({periodOption: options});
    }

    _handleEchartsOption(charts) {
        let xAxisData = [], seriesData = [];
        for (let i = 0; i < charts.length; i++) {
            xAxisData.push(charts[i].OP_TIME);
            seriesData.push(charts[i].INDEX_VALUE);
        }
        const option = {
            grid: {top: 20, bottom: 20, right: 20,left:60},
            tooltip: {
                show: true,
                trigger: 'axis',
                formatter: '{c}',
                backgroundColor: 'rgba(0,0,0,0)',
                textStyle: {color: Style.color.blue},
                position: function (point, params, dom, rect, size) {
                    return [point[0], 5];
                },
                axisPointer: {type: 'line', lineStyle: {color: Style.color.lightGray}}
            },
            xAxis: {
                type: 'category',
                axisLabel: {textStyle: {color: Style.color.gray}},
                axisLine: {show: false},
                axisTick: {show: false},
                splitLine: {show: false},
                data: xAxisData
            },
            yAxis: {
                type: 'value',
                axisLabel: {textStyle: {color: Style.color.gray}},
                axisLine: {show: false},
                axisTick: {show: false},
                splitLine: {show: false}
            },
            series: [{
                type: 'line',
                smooth: true,
                data: seriesData
            }],
            color: [Style.color.blue]
        };
        if (xAxisData.length > 0 && seriesData.length > 0) {
            this.setState({echartsOption: option});
        }
    }

    _handleChangePeriod(index) {
        this.setState({indicator: {visible: true, message: ''}});
        this.setState({selectPeriodIndex: index});
        this.param.opTime = this.state.periodOption[index].value;
        this._loadScreenData();
    }

    _appendDownLevel(orgId, orgName) {
        this.setState({indicator: {visible: true, message: ''}});
        this.setState({downLevel: this.state.downLevel.concat([{orgId: orgId, orgName: orgName}])});
        this.param.orgId = orgId;
        this._loadScreenData();
    }

    _sliceDownLevel(orgId, orgName, index) {
        this.setState({indicator: {visible: true, message: ''}});
        this.setState({downLevel: this.state.downLevel.slice(0, index + 1)});
        this.param.orgId = orgId;
        this._loadScreenData();
    }

    render() {
        return (
            <View style={styles.container}>
                {/*<View style={styles.DropDownView}>
                    <DropDown color={Style.color.blue} title="请选择账期" data={this.state.periodOption}
                              defaultIndex={this.state.selectPeriodIndex}
                              onConfirm={(index) => this._handleChangePeriod(index)}/>
                </View>*/}
                <View style={{flex:1,}}>
                    <View style={styles.IndexLineView}>
                        <View style={styles.IndexLineHeaderView}>
                            <Text>{this.state.indexName}</Text>
                        </View>
                        <View style={{height:180}}>
                            {
                                this.state.indicator.visible || (this.state.echartsOption.xAxis && this.state.echartsOption.xAxis.data.length > 0 && !this.state.indicator.visible) ?
                                    <Echarts option={this.state.echartsOption} height={180} width={Dimensions.get('window').width}/>
                                    :
                                    <Indicator isVisible={true} message={Style.tip.noData} type="none"/>
                            }
                        </View>
                    </View>

                    <Breadcrumbs title="当前位置" data={this.state.downLevel}
                                 onPress={(orgId,orgName,index) => {this._sliceDownLevel(orgId,orgName,index)}}/>

                    <View style={styles.IndexRandView}>
                        <IndexRandHeader value={this.state.indexData.value} ratio={this.state.indexData.ratio}/>
                        {
                            this.state.indicator.visible || (this.state.tableData && this.state.tableData.length > 0) ?
                                <ScrollView style={{flex:1}}>
                                    {this.state.tableData && this.state.tableData.map((item, index) => (
                                        <IndexRandItem rank={item.INDEX_ORDER} id={item.ORG_ID} name={item.ORG_NAME}
                                                       value={item.INDEX_VALUE} ratio={item.SPECIFICVALUE} index={index}
                                                       onPress={(orgId,orgName) => this._appendDownLevel(orgId,orgName)}
                                                       downloadFlag={this.state.downloadFlag}
                                                       key={`OperateIndexItem_${index}`}/>
                                    ))}
                                </ScrollView>
                                :
                                <Indicator isVisible={true} message={Style.tip.noData} type="none"/>
                        }
                    </View>
                </View>
                <Indicator isVisible={this.state.indicator.visible} message={this.state.indicator.message}/>
            </View>
        );
    }
}

class IndexRandHeader extends Component {
    render() {
        return (
            <View style={styles.IndexRandHeaderView}>
                <View style={{width:'15%'}}>
                    <Text style={[styles.IndexRandHeaderTH]}>排名</Text>
                    <Text>1</Text>
                </View>
                <View style={{width:'25%'}}>
                    <Text style={[styles.IndexRandHeaderTH,{color:Style.color.blue,fontSize:Style.fontSize.large}]}>成都</Text>
                </View>

                <View style={{width:'35%'}}>
                    <Text style={[styles.IndexRandHeaderTH]}>到达值</Text>
                    <Text style={styles.IndexRandHeaderValue}>{Tool.numberFormat(this.props.value, 0)}</Text>
                </View>
                <View style={{width:'25%'}}>
                    <Text style={styles.IndexRandHeaderTH}>同比增幅</Text>
                    <View style={{alignItems:'flex-start',justifyContent:'center'}}>
                        <View
                            style={[styles.IndexRandHeaderRatio]}>
                            <MaterialIcon name={this.props.ratio >= 0 ? 'arrow-upward' : 'arrow-downward'} size={14}
                                          color={Style.color.white}/>
                            <Text style={{color:Style.color.white,fontSize:Style.fontSize.small}}>
                                {Tool.numberFormat(Math.abs(this.props.ratio * 100), 2)}%
                            </Text>
                        </View>
                    </View>
                </View>
            </View>
        );
    }
}

class IndexRandItem extends Component {
    render() {
        const color = [Style.color.red, Style.color.yellow, Style.color.green]
        let children = (
            <View style={styles.IndexRandItemView}>
                <View style={{width:'15%'}}>
                    <Text style={[styles.IndexRandItemTD,this.props.index < 3 ? {color:color[this.props.index%3]} : {}]}>
                        {this.props.rank}
                    </Text>
                </View>
                <View style={{width:'25%'}}>
                    <Text style={[styles.IndexRandItemTD,{color:Style.color.heightBlue}]}>{this.props.name}</Text>
                </View>

                <View style={{width:'35%'}}>
                    <Text style={[styles.IndexRandItemTD,{color:Style.color.black}]}>{Tool.numberFormat(this.props.value, 0)}</Text>
                </View>
                <View style={[styles.IndexRandItemRight,{width:'25%',alignItems:'center'}]}>
                    <Text style={styles.IndexRandItemTD}>
                        {Tool.numberFormat(Math.abs(this.props.ratio * 100), 2)}%
                    </Text>
                    {this.props.downloadFlag ?
                        <SimpleLineIcons name='arrow-right' size={12} color={Style.color.gray}/> : null}
                </View>
            </View>
        );
        let randItem = this.props.downloadFlag ?
            <TouchableHighlight underlayColor={Style.color.lightGray}
                                onPress={() => {this.props.onPress(this.props.id,this.props.name)}}>
                {children}
            </TouchableHighlight>
            :
            children;
        return randItem;
    }
}

/**
 * 面包屑导航考虑抽象组件
 */
class Breadcrumbs extends Component {
    render() {
        let data = this.props.data;
        return (
            <View style={{flexDirection:'row',marginTop:10}}>
                <Text style={{fontSize:Style.fontSize.small,color:Style.color.black}}>{this.props.title}</Text>
                {data && data.map((item, index, array) => (
                    <View style={{flexDirection:'row'}} key={`BreadcrumbItem_${index}`}>
                        <Text style={{fontSize:Style.fontSize.small,color:Style.color.gray}}> > </Text>
                        {
                            array.length - 1 === index ?
                                <Text
                                    style={{fontSize:Style.fontSize.small,color:Style.color.gray}}>{item.orgName}</Text>
                                :
                                <TouchableOpacity onPress={() => {this.props.onPress(item.orgId,item.orgName,index)}}>
                                    <Text
                                        style={{fontSize:Style.fontSize.small,color:Style.color.blue}}>{item.orgName}</Text>
                                </TouchableOpacity>
                        }
                    </View>
                ))}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1, backgroundColor: Style.color.screen
    },
    DropDownView: {
        flexDirection: 'row', justifyContent: 'center', alignItems: 'center'
    },
    IndexLineView: {
        borderWidth: 1, borderColor: Style.color.shadow, backgroundColor: Style.color.white
    },
    IndexLineHeaderView: {
        borderBottomWidth: 1, borderColor: Style.color.lightGray, paddingHorizontal: 10, paddingVertical: 5,height:50,
        justifyContent:'center'
    },
    IndexLineHeaderTitle: {
        color: Style.color.gray, fontSize: Style.fontSize.normal,
    },
    IndexRandView: {
        flex: 1,
        marginTop: 10,
        borderWidth: 1,
        borderColor: Style.color.shadow,
        backgroundColor: Style.color.white,
        // borderRadius: 5
    },
    IndexRandHeaderView: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 10,
        paddingHorizontal: 10,
        borderBottomWidth: 1,
        borderColor: Style.color.lightGray
    },
    IndexRandHeaderTH: {
        fontSize: Style.fontSize.normal, color: Style.color.gray
    },
    IndexRandHeaderValue: {
        fontSize: Style.fontSize.normal, color: Style.color.heightBlue
    },
    IndexRandHeaderRatio: {
        flexDirection: 'row',
        paddingHorizontal: 10,
        paddingVertical: 1,
    },
    IndexRandItemView: {
        borderBottomWidth: 1,
        borderColor: Style.color.lightGray,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 10
    },
    IndexRandItemTD: {
        fontSize: Style.fontSize.normal, color: Style.color.gray
    },
    IndexRandItemRight: {
        flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'
    }
});